<template>
	<view v-show="!loading">
		<ad adpid="1206517737" type="banner"></ad>
		<!-- 插屏广告 -->
		<ad-common-interstitial ref="adInatance"></ad-common-interstitial>
		<view v-if="wifiList.data.length">
			<view class="search">
				<uni-easyinput suffixIcon="search" v-model="keyword" placeholder="请输入商户/WiFi名称查询"
					@iconClick="getWifiList"></uni-easyinput>
			</view>

			<view v-for="wifi in wifiList.data" :key="wifi._id" class="item">
				<view class="content">
					<view class="left">
						<view class="provider">

							{{
							wifi.provider_name
						}}
						</view>
						<view class="wifi-name">
							<text>
								WiFi名称：
							</text>
							<text>{{
							wifi.wifi_name
						}}</text>
						</view>
						<!-- 只有用户自己创建的wifi才显示当前创建了多少次，否则不显示 -->
						<view class="connect-count" v-if="isUserWifi(wifi)">
							累计连接<text>
								{{
									wifi.connect_count
								}}
							</text>次
						</view>
					</view>
					<view class="right">
						<image :src="wifi.qrcode_file" mode="aspectFit" style="width:100%;height:250rpx;"
							:lazy-load="true"></image>
					</view>
				</view>
				<!-- 消费者不能删除和管理wifi这几个按钮隐藏 -->
				<view class="btn-tool" v-if="isUserWifi(wifi)">
					<button type="primary" size="mini" @click="modifyWifi(wifi)" plain="true">修改</button>
					<button type="default" size="mini" class="not-first" @click="wifiSetiing(wifi)"
						plain="true">管理</button>
					<button type="warn" size="mini" class="not-first" @click="deleteWifi(wifi._id)"
						plain="true">删除</button>
				</view>



			</view>
		</view>
		<view v-else class="no-data">
			<view>
				<uni-icons custom-prefix="iconfont" type="icon-zanwushuju" size="48" color="#999999"></uni-icons>
			</view>
			<view class="text">
				暂无数据
			</view>
		</view>
	</view>
</template>

<script>
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app';

	import {
		ref,
		reactive,
		toRef
	} from 'vue';
	import {
		roleMap
	} from "@/common/mapUtils.js"
	// 引入插屏广告
	// import {interstitial} from "@/common/ad.js"
	const db = uniCloud.database();
	const wifiTable = db.collection('wifi')
	const usersTable = db.collection('uni-id-users')
	const wifiConnectTable = db.collection('wifi_connect_records')
	
	export default {
		setup() {
			uni.showLoading({
				mask: true
			});
			let loading = ref(true)
			const keyword = ref("")
			// 插屏广告组件
			const adInatance = ref(null)

			const wifiList = reactive({
				data: []
			})
			let connectedData = []
			let wifiData = toRef(wifiList, "data")
			// 初始化插屏广告
			// onReady(() => {
			// 	// 创建广告实例
			// 	interstitial.load("1076934123")
			// })
			onLoad(() => {
				getWifiList()
				uni.$on('reloadWifiList', () => {
					getWifiList()
				});
				// 2秒后显示插屏广告，报错就算了，只执行一次就行
				// setTimeout(() => {
				// 	interstitial.show()
				// }, 2000)
				setTimeout(() => {
					adInatance.value.show()
				}, 1000)

			})

			const getWifiList = async () => {
				const user = usersTable.where("'_id' == $cloudEnv_uid").getTemp();

				db.collection(user, 'wifi').get().then((res) => {

					// wifiTable.where('qrcode_file != null').get().then((res) => {
					// console.log("res获取wifi列表", res)
					const wifiata = res.result.data[0].wifi || []
					// 加了按商户名称和wifi名称模糊查询
					wifiList.data = keyword.value ? wifiata.filter((item) => {
						return item.provider_name.includes(keyword.value) || item.wifi_name
							.includes(keyword.value)
					}) : wifiata
					// console.log("wifiList.data",wifiList.data)
					// console.log("keyword",keyword.value)
					// 获取wifi连接数量
					getWifiConnectData()
					loading.value = false
				}).catch(() => {
					loading.value = false
				}).finally(() => {
					uni.hideLoading()
				})
			}

			const modifyWifi = (wifi) => {
				const params = JSON.parse(JSON.stringify(wifi))
				delete params.qrcode_file
				uni.navigateTo({
					url: "/subpkgWifi/createWifi/createWifi?wifi=" + encodeURIComponent(JSON.stringify(params))
				})
			}

			const wifiSetiing = (wifi) => {
				uni.navigateTo({
					url: "/subpkgWifi/wifiSetting?_id=" + wifi._id
				})
			}

			const deleteWifi = async (_id) => {
				uni.showModal({
					title: '温馨提示',
					content: '建议您修改WiFi密码账户信息更新WiFi，删除后已打印的码牌将失效。确定删除吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await wifiTable.where({
									_id
								}).remove()
								// 删除后同步更新user表的wifi字段数据
								updateUserWifi(_id)
								uni.showToast({
									title: '删除成功'
								})
								getWifiList()
							} catch (e) {
								uni.showModal({
									title: '提示',
									content: e.message
								})
							}
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});

			}

			const updateUserWifi = async (_id) => {
				const {
					result
				} = await usersTable.where("'_id'==$cloudEnv_uid").get()
				const wifi = result.data[0].wifi || []
				const deleteResult = wifi.filter(item => item !== _id)
				// console.log("wifi", wifi)
				usersTable.where('_id==$cloudEnv_uid').update({
					wifi: deleteResult
				}).then(res => {
					// console.log("更新用户的wifi完成", res)
				})
			}

			// 判断是否是当前用户自己创建的wifi，不是自己的没有修改权限
			const isUserWifi = (wifi) => {
				// 判断用户是否是提供者，提供者显示按钮，消费者不显示
				const userInfo = uni.getStorageSync("userInfo")
				if (userInfo && userInfo._id) {
					if (!wifi.created_user) {
						return true
					} else {
						return wifi.created_user === userInfo._id
					}
				} else {
					return false
				}
			}
			
			// 获取单个wifi的连接次数
			const getWifiCount = (wifi)=>{
				const result = connectedData.find((item)=>{
					return wifi._id === item.wifi_id
				})
				if(!result){
					return 0
				}else{
					return result.wifi_connect_count||0
				}
			}
			// 获取当前wifi的累计连接次数
			const getWifiConnectData = async (wifi) => {
				const res = await wifiConnectTable
				.groupBy('wifi_id')
				.groupField('count(*) as wifi_connect_count')
				.get()
				
              // const result = await wifiConnectTable.where(`wifi_id==${wifi._id}`).count()
			  // console.log("获取当前wifi累计连接数量",res)
			  connectedData = res.result.data || []
			  // 设置wifi的连接数量
			  // console.log(wifiData.value)
			  wifiData.value.forEach((item)=>{
				  // console.log(item)
				  item.connect_count = getWifiCount(item)
			  }
			  )
			}

			return {
				wifiData,
				wifiList,
				modifyWifi,
				deleteWifi,
				wifiSetiing,
				loading,
				isUserWifi,
				getWifiList,
				keyword,
				adInatance,
				getWifiCount
				// showInterstitialAd
			}
		}
	}
</script>

<style lang="scss">
	.item {
		background-color: #ffffff;
		border-radius: 20rpx;
		margin: 50rpx 32rpx;
		padding: 25rpx 25rpx;
		height: 300rpx;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: space-between;
	}

	.content {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		justify-content: space-between;
		flex: 1;
		width: 100%;
	}

	.left {
		flex: 1;
	}

	.right {
		height: 250rpx;
		width: 40%;
	}

	.provider {
		font-size: 36rpx;
	}

	.wifi-name {
		color: #999999;
		font-size: 32rpx;
		margin-top: 16rpx;
	}

	.connect-count {
		margin-top: 24px;
		color: #666666;

		text {
			font-style: italic;
			color: $uni-color-primary;
			padding: 0 8px;
			font-weight: bold;
			font-size: 36rpx;
		}
	}

	.btn-tool {
		height: 50rpx;

		button.not-first {
			margin-left: 28rpx;
		}
	}

	.no-data {
		flex-direction: column;
		display: flex;
		align-items: center;
		justify-content: center;
		padding-top: 48rpx;
	}

	.text {
		margin-top: 10px;
		color: #666666;
	}

	.search {
		margin: 50rpx 32rpx;
	}
</style>
